package com.google.code.sharecontent.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.google.code.sharecontent.dao.StatusDao;
import com.google.code.sharecontent.model.Status;

public class StatusDaoImpl extends BaseDaoImpl<Status> implements StatusDao {

	public StatusDaoImpl(Connection conn) {
		super(conn);
	}

	
	public Map<String, String> getContentStatuses(Integer resourceId) {
		Map<String, String> result = new HashMap<String, String>();
		if (resourceId != null) {
			String sql ="select s.ID,s.CODE,s.NAME,count(*) as kol from CONTENTS as c " + 
						" left join STATUSES as s on s.ID=c.STATUS_ID " +
						" where RESOURCE_ID = ? " +
						" group by s.ID,s.CODE,s.NAME";
			result.put("","");
			try {
				PreparedStatement ps = this.conn.prepareStatement(sql);
				ps.setInt(1, resourceId);
				ResultSet rs = ps.executeQuery();
				while (rs.next()) {
					result.put(rs.getString("NAME")+" -"+rs.getInt("kol"), rs.getString("CODE"));
				}
			} catch (SQLException e) {
				logger.error(e.getMessage());
			}
		}
		return result;
	}
	/**
	 * FIXME сделать карзинку, для экономии обращений к базе
	 * @throws SQLException 
	 */
	public Status getByCode(String code) throws SQLException {
		ArrayList<Status> list = this.list("code = '"+code+"'", "ID");
		if (list != null && list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	
	@Override
	public Status createByRow(ResultSet rs) throws SQLException {
		Status status = new Status();
		status.setId(rs.getInt("ID"));
		status.setName(rs.getString("NAME"));
		status.setCode(rs.getString("CODE"));
		return status;
	}

	@Override
	protected String generateInsertSql(Status status) {
		return "insert into "+getTableName()+" (NAME, CODE) values (?,?)";
	}
	
	@Override
	protected String generateUpdateSql(Status status) {
		return "update "+getTableName()+" set NAME = ?,CODE = ? "+
		" where ID = "+ status.getId();
	}
	
	@Override
	protected String getTableName() {
		return "STATUSES";
	}

	@Override
	protected PreparedStatement putPrepareStatement(PreparedStatement pStat,
			Status status) throws SQLException {
		pStat.setString(1, status.getName());
		pStat.setString(2, status.getCode());
		return pStat;
	}
}
